package com.aaron.messenger.ui;

import com.aaron.messenger.MessengerApplication;
import com.aaron.messenger.data.ChatMessage;
import com.aaron.messenger.data.DataManager;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Window;
import android.view.WindowManager;

public abstract class BindServiceActivity extends Activity {

	protected DataManager mManager;
	
	private Handler mH = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case DataManager.MessageDispatcher.MSG_USER_LOGIN:
			case DataManager.MessageDispatcher.MSG_USER_QUIT:
			case DataManager.MessageDispatcher.MSG_USER_FEEDBACK:
				onUserListChanged();
				break;
			case DataManager.MessageDispatcher.MSG_RECEIVE_DATA:
				onReceiveData((ChatMessage)msg.obj);
				break;
			}
		}
	};
	
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		connectToService();
	}
	
	private void connectToService() {
		startService(new Intent(this, DataManager.class));
		bindService(new Intent(this, DataManager.class), mConnection, Service.BIND_AUTO_CREATE);
	}
	
	public void stopMessagerService() {
		mManager.logout();
		unbindService(mConnection);
		stopService(new Intent(this, DataManager.class));
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			mManager = ((DataManager.LocalBinder) service).getDataManager();
			mManager.setCallBackHandler(mH);
			if(!mManager.isLogin()) {
				mManager.login();
			}
			onMessagerServiceConnected();
		}

		public void onServiceDisconnected(ComponentName className) {
			mManager.setCallBackHandler(null);
			mManager = null;
		}
	};
	
	protected void onMessagerServiceConnected() {
		
	}
	
	protected void onUserListChanged() {
		
	}
	
	protected void onReceiveData(ChatMessage msg) {
		
	}
	
	public void onConfigurationChanged(Configuration config) {
	    super.onConfigurationChanged(config);
	}
	   
	public void onResume() {
		super.onResume();
		((MessengerApplication)getApplication()).setCurrentActivity(getClass().getName());
	}
	
	public void onStop() {
		super.onStop();
		((MessengerApplication)getApplication()).setCurrentActivity(null);
	}
	
	public void onBackPressed() {
		quit();
	}
	
	public void quit() {
		unbindService(mConnection);
		finish();
	}
}
